//
//  BBSimpleBlobTracker.m
//  BBTouch
//
//  Created by ben smith on 8/18/08.
//  This file is part of BBTouch.
//
//  BBTouch is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.

//  BBTouch is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.

//  You should have received a copy of the GNU Lesser General Public License
//  along with BBTouch.  If not, see <http://www.gnu.org/licenses/>.
// 
//  Copyright 2008 Ben Britten Smith ben@benbritten.com .
//

#import "BBSimpleBlobTracker.h"
#import "BBBlobEvent.h"


@implementation BBSimpleBlobTracker

@synthesize delegate;
@synthesize blobPoints;

- (id) init
{
	self = [super init];
	if (self != nil) {
		[self setup];
	}
	return self;
}

-(void)awakeFromNib
{
	[self setup];
}

-(void)setup
{
	self.blobPoints = [NSMutableArray array];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(blobDown:) name:@"BBBlobDown" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(blobUp:) name:@"BBBlobUp" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(blobDragged:) name:@"BBBlobDragged" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(blobDone:) name:@"BBBlobMovementFinished" object:nil];
}

///////////////////////////////////////////////
// blob notification methods
// TODO: add some checks to make sure that I am getting proper blob objects and not
// being called from somewhere that might not be a blob event

-(void)blobDown:(NSNotification*)note
{
	// add the blob to my list
	[blobPoints addObject:[note object]];
}

-(void)blobUp:(NSNotification*)note
{
	int blobIndex = [self indexOfBlobWithID:[[note object] blobID]];
	if (blobIndex != NSNotFound) {
		[blobPoints removeObjectAtIndex:blobIndex];
	}
}

-(void)blobDragged:(NSNotification*)note
{
	// replace the old blob with the new blob info
	int blobIndex = [self indexOfBlobWithID:[[note object] blobID]];
	if (blobIndex != NSNotFound) {
		[blobPoints replaceObjectAtIndex:blobIndex withObject:[note object]];
	}
}

// quick convenience method to grab blob indexes
-(int)indexOfBlobWithID:(int)blobId
{
	int blobIndex;
	for (blobIndex = 0; blobIndex < [blobPoints count]; blobIndex++) 
		if ([[blobPoints objectAtIndex:blobIndex] blobID] == blobId) return blobIndex;
	return NSNotFound;	
}

-(void)blobDone:(NSNotification*)note
{
	if ([delegate respondsToSelector:@selector(blobCycleDone)])
		[delegate blobCycleDone];
}

- (void) dealloc
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[delegate release];
	[super dealloc];
}


@end
